﻿using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
using System.Windows.Markup;
using Foundation.MarkupExtensions;

namespace Foundation.Converters
{
    [ContentProperty("Cases")]
    public class SwitchConverter : IValueConverter
    {
        public SwitchConverter()
        {
            Cases = new CaseList();
        }

        public CaseList Cases { get; set; }

        public object Default { get; set; }

        public bool TypeMode { get; set; }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (TypeMode) value = value == null ? null : value.GetType();
            var pair =
                Cases.FirstOrDefault(
                    p =>
                    Equals(p.Key, value) ||
                    (p.Key != null && value is ValueType &&
                     Equals(value, TypeDescriptor.GetConverter(value.GetType()).ConvertFromString(p.Key.ToString()))));
            return pair == null ? Default : pair.Value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
